package com.guiwu.caiguanlin.leetcode;

/**
 * 查找字符串数组中的最长公共前缀
 */
public class Test14 {

    public static void main(String[] args) {

//        String[] strs = {"flower", "flow", "flight"}; //""
        String[] strs = {"flower","flow","flight"}; //fl
        String str = getLongestCommonPrefix(strs);
        System.out.println(str);

    }

    /**
     * 获取字符串数组中最长公共前缀
     * @param strArr
     * @return
     */
    public static String getLongestCommonPrefix(String[] strArr) {
        if (strArr == null || strArr.length == 0) {
            return "";
        }
        String prefix = strArr[0];
        for (int i = 1; i < strArr.length; i++) {
            prefix = getLongestCommonPrefix(prefix, strArr[i]);
            //如果是空串，直接跳出循环
            if (prefix.length() == 0){
                break;
            }
        }
        return prefix;
    }

    /**
     * 求两个字符串中的公共前缀
     * @param str1
     * @param str2
     * @return
     */
    public static String getLongestCommonPrefix(String str1, String str2) {
        //取两个字符串中最短的字符串长度
        int minLength = Math.min(str2.length(), str1.length());
        int index = 0;
        //index < minLength是为了减少没必要的循环
        while (index < minLength && str1.charAt(index) == str2.charAt(index)) {
            index++;
        }
        return str1.substring(0, index);
    }
}
